﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：OAuthBearerAuthenticationMiddlewareExtended.cs
// 功能描述：TongTongMall.Oauth2.0
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Microsoft.Owin.Security.Infrastructure;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Owin;
using Microsoft.Owin.Security.DataHandler;

namespace TongTongMall.Oauth2._0
{
    public class OAuthBearerAuthenticationMiddlewareExtended : AuthenticationMiddleware<OAuthBearerAuthenticationOptions>
    {
        private readonly ILogger _logger;
        private readonly string _challenge;
        public OAuthBearerAuthenticationMiddlewareExtended(OwinMiddleware next, IAppBuilder app, OAuthBearerAuthenticationOptions options) : base(next, options)
        {
            _logger = app.CreateLogger<OAuthBearerAuthenticationMiddlewareExtended>();
                //AppBuilderLoggerExtensions.CreateLogger<OAuthBearerAuthenticationMiddlewareExtended>(app);
            _challenge = string.IsNullOrWhiteSpace(Options.Challenge) ? (!string.IsNullOrWhiteSpace(Options.Realm) ? "Bearer realm=\"" + this.Options.Realm + "\"" : "Bearer") : this.Options.Challenge;

            if (Options.Provider == null)
                Options.Provider = new OAuthBearerAuthenticationProvider();

            if (Options.AccessTokenFormat == null)
                Options.AccessTokenFormat = new TicketDataFormat(
                    Microsoft.Owin.Security.DataProtection.AppBuilderExtensions.CreateDataProtector(app, typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1"));

            if (Options.AccessTokenProvider != null)
                return;

            Options.AccessTokenProvider = new AuthenticationTokenProvider();
            //_logger.WriteCore()
        }

        protected override AuthenticationHandler<OAuthBearerAuthenticationOptions> CreateHandler()
        {
            return new OAuthBearerAuthenticationHandlerExtended(_logger, _challenge);
        }


    }
}
